package com.fanfan.SmartPensionSystembackend.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fanfan.SmartPensionSystembackend.entity.Family;
import com.fanfan.SmartPensionSystembackend.entity.FamilyInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.stream.Collectors;

@Mapper
public interface FamilyMapper extends BaseMapper<Family> {
    @Select("SELECT MAX(familyId) FROM family")
    String getMaxFamilyId();

    @Insert({
        "INSERT INTO family (familyId, elderId, name, relationship, phone)",
        "VALUES (#{familyId}, #{elderId}, #{name}, #{relationship}, #{phone})"
    })
    int insert(Family family);

    // 根据 elderId 查询家属列表
    default List<FamilyInfo> getFamilyByElderId(String elderId) {
        return selectList(new LambdaQueryWrapper<Family>()
                .select(Family::getName, Family::getRelationship, Family::getPhone)
                .eq(Family::getElderId, elderId)
        ).stream()
                .map(f -> new FamilyInfo(f.getName(), f.getRelationship(), f.getPhone()))
                .collect(Collectors.toList());
    }

    // 更新家属信息
    @Update({
        "UPDATE family SET name = #{name}, relationship = #{relationship}, phone = #{phone} ",
        "WHERE elderId = #{elderId}"
    })
    void updateFamilyInfo(FamilyInfo familyInfo);

    // 根据 elderId 删除家属信息
    @Delete("DELETE FROM family WHERE elderId = #{elderId}")
    void deleteByElderId(String elderId);
}